from flask import Flask, render_template, request, jsonify
from datetime import timedelta
from QRcode_detector import singe_image
import os

app = Flask(__name__)


# 输出
@app.route('/')
def hello_world():
    return 'Hello World!'


# 设置允许的文件格式
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'bmp'])


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


# 设置静态文件缓存过期时间
app.send_file_max_age_default = timedelta(seconds=1)

isSaveImage = False
img_count = 0

def save_Image(File):
    # 当前文件所在路径
    basepath = os.path.dirname(__file__)
    # 一定要先创建该文件夹，不然会提示没有该路径
    upload_dir = os.path.join(basepath, 'static/images')
    if not (os.path.exists(upload_dir)):
        os.makedirs(upload_dir)
    upload_path = os.path.join(upload_dir, File.filename)
    # 保存文件
    File.save(upload_path)
    print(upload_path)


# 添加路由
@app.route('/upload', methods=['POST', 'GET'])
def upload():
    if request.method == 'POST':
        # 通过file标签获取文件
        f = request.files['file']
        f_byte = f.read()
        singe_image(f_byte)

        if isSaveImage:
            save_Image(f)
        return "success"
    # 重新返回上传界面
    return render_template('upload.html')


if __name__ == '__main__':
    app.run(host="0.0.0.0")
